package com.hefei.aop.aop;

import com.hefei.aop.annotation.GmallCache;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author caizhengjun
 * @date 2020/9/5 3:53 下午
 */
@Component
@Aspect
public class UserAspect {

    @Pointcut("@annotation(com.hefei.aop.annotation.GmallCache)")
    public void pointcut() {
    }

    @Before("pointcut()")
    public void before() {
        System.out.println("前置通知....");//2
    }

    @AfterReturning(value = "pointcut()", returning = "returnVal")
    public void AfterReturning(Object returnVal) {
        System.out.println("后置通知...." + returnVal);//4
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {

        //获取切点方法的签名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获取方法对象
        Method method = signature.getMethod();
        //获取方法上指定注解的对象
        GmallCache annotation = method.getAnnotation(GmallCache.class);
        //获取注解中的前缀
        String prefix = annotation.prefix();
        //获取方法的参数
        Object[] args = joinPoint.getArgs();

        System.out.println("环绕通知前....");//1
        Object obj = (Object) joinPoint.proceed();//3

        System.out.println("环绕通知后....");
        return obj;
    }

    @AfterThrowing(value = "pointcut()", throwing = "e")
    public void afterThrowable(Throwable e) {
        System.out.println("出现异常:msg=" + e.getMessage());
    }

    @After("pointcut()")
    public void after() {
        System.out.println("最终通知....");
    }
}
